package org.seamon.management.controller;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.seamon.management.pojo.dto.LoginDTO;
import org.seamon.management.pojo.dto.UserInsertDto;
import org.seamon.management.pojo.vo.TokenVO;
import org.seamon.management.service.UserService;
import org.seamon.management.service.impl.AuthService;
import org.seamon.management.util.Result;
import org.seamon.management.util.aspect.Limit;
import org.seamon.management.util.aspect.Log;
import org.seamon.management.util.enums.BusinessTypeEnum;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

/**
 * @author Simon
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Resource
    private UserService userService;

    @Resource
    private AuthService authService;

    @Limit(key = "register", permitsPerSecond = 20, timeout = 60, timeunit = TimeUnit.SECONDS)
    @Log(title = "用户注册", businessType = BusinessTypeEnum.REGISTER)
    @PostMapping("/register")
    public Result<?> register(@RequestBody @Valid UserInsertDto dto) {
        log.info("注册用户信息：{}", dto);
        userService.saveUser(dto);
        return Result.success();
    }

    @Limit(key = "login", permitsPerSecond = 30, timeout = 60, timeunit = TimeUnit.SECONDS)
    @Log(title = "用户登录", businessType = BusinessTypeEnum.LOGIN)
    @PostMapping("/login")
    public Result<?> login(@RequestBody LoginDTO loginDTO) {
        log.info("登录用户信息：{}", loginDTO);
        TokenVO tokenVO = authService.login(loginDTO);
        return Result.success(tokenVO);
    }

    @Log(title = "用户登出", businessType = BusinessTypeEnum.UPDATE)
    @GetMapping("/refresh-token")
    public Result<?> refreshToken(@RequestHeader("Authorization") String oldRefreshToken) {
        log.info("刷新Token");
        String token = oldRefreshToken.substring(7);
        TokenVO tokenVO = authService.refreshToken(token);
        return Result.success(tokenVO);
    }

    @Limit(key = "logout", permitsPerSecond = 10, timeout = 1, timeunit = TimeUnit.SECONDS)
    @Log(title = "用户登出", businessType = BusinessTypeEnum.LOGOUT)
    @PostMapping("/logout")
    public Result<?> logout(@RequestHeader("Authorization") String token) {
        log.info("登出用户信息：{}", token);
        authService.logout(token);
        return Result.success("登出成功");
    }
}
